import socket
from net.msg_handle import msg_handle


def main():
    encoding = 'utf-8'

    # Create a TCP/IP socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind the socket to a port
    server_address = ('localhost', 8888)

    if 0:
        from shells.sshKillOldProcessing import run as kill_old_processing
        kill_old_processing(port=server_address[-1])

    server.bind(server_address)

    print(f'--- 正在监听 {server_address}')

    # Listen for incoming connections
    server.listen(1)

    while True:
        # Wait for a connection
        connection, client_address = server.accept()
        if msg_handle.client_connection is not None:
            msg_handle.client_connection = connection
        try:
            # Receive data in small chunks and print it
            while True:
                data = connection.recv(1024)
                if data:
                    # connection.send(data)
                    if 1:
                        """
                        数据处理
                        """
                        data: bytes
                        msg_str = data.decode(encoding)
                        print('--- received data: ', msg_str)

                        msg_handle.run(data)
                        # MsgHandle.send(connection, msg_str)
                else:
                    # No more data, close the connection
                    break
        finally:
            # Clean up the connection
            connection.close()


if __name__ == '__main__':
    main()


